package com.spark.incoicings.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.spark.incoicings.service.*;
import com.spark.incoicings.vo.CustomerStatementVo;
import com.spark.invoicings.entity.*;
import com.spark.invoicings.utils.Result;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 *
 * 客户对账单和明细
 *
 */
@RestController
@RequestMapping("/SalesReceipt")
public class CustomerStatementController {
    @Resource
    private CustomerStatementService css;
    @Resource
    private CustomerStatementDetailService csd;
    @Resource
    private SaleCustomerService sc;
    @Resource
    private DictDataService ds;
    @Resource
    private ProductService ps;
    @Resource
    private ReceivablePayableDetailService rps;
    @Resource
    private OutboundDetailService outds;
    @Resource
    private InboundDetailService ids;
    @Resource
    private OutboundOrderService oos;
    @Resource
    private WarehouseReceiptService wrs;

    /**
     * 分页条件查询客户对账单
     * */
    @GetMapping("/selectCustomerStatement")
    public Result selectCustomerStatement(
            @RequestParam(defaultValue = "1")Integer pageNum,
            @RequestParam(defaultValue = "6")Integer pageSize,
            @RequestParam(value = "customerId",required = false) Integer customerId){
        PageHelper.startPage(pageNum,pageSize);
        Map<String,Object> map=new HashMap<>();
        map.put("customerId",customerId);
        PageHelper.orderBy("customer_statement_id desc");
        List<CustomerStatement> list= css.selectCustomerStatement(map);
        for (CustomerStatement c:list){
            c.setCustomerStatementDetails(csd.selectId(c.getCustomerStatementId()));
            c.setSaleCustomer(sc.getById(c.getCustomerId()));
        }
        PageInfo<CustomerStatement> page=new PageInfo<>(list);
        return Result.success(200,"success",page);
    }

    /**
     * 添加客户对账单
     * */
    @PostMapping("/saveCustomerStatement")
    @Transactional
    public Result saveCustomerStatement(@RequestBody CustomerStatementVo request) {
        CustomerStatement c = request.getCustomerStatement();
        List<CustomerStatementDetail> customerStatementDetails = request.getCustomerStatementDetails();

        // 保存客户对账单
        c.setBillNumber(generateBillNumber()); // 生成账单号
        css.save(c); // 保存对账单

        // 获取保存后的对账单ID
        int customerStatementId = c.getCustomerStatementId();

        double totalAmount = 0; // 本期应收金额
        double currentReceivedAmount = 0; // 已收款总额
        double currentPendingAmount = 0; // 本期待收金额

        // 保存客户对账单明细，并设置对账单ID
        for (CustomerStatementDetail cd : customerStatementDetails) {
            totalAmount += cd.getTotalAmount();
            currentPendingAmount += cd.getPendingAmount();
            currentReceivedAmount += cd.getReceivedAmount();

            ReceivablePayableDetail r = rps.getById(cd.getSalesOrderId());
            if(r!=null){
                cd.setReceivedAmount(r.getReceivedTotalAmount());
                cd.setPendingAmount(r.getPendingCollectionTotalAmount());
            }
            // 设置对账单ID
            cd.setCustomerStatementId(customerStatementId);
        }

        // 批量保存对账单明细
        csd.saveBatch(customerStatementDetails);

        // 更新客户对账单的金额信息
        c.setCurrentReceivableAmount(totalAmount);
        c.setCurrentReceivedAmount(currentReceivedAmount);
        c.setCurrentPendingAmount(currentPendingAmount);
        css.updateById(c); // 更新客户对账单，MyBatis-Plus 的更新方法

        return Result.success();
    }


    private String generateBillNumber() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyMMdd");
        String dateStr = sdf.format(new Date());

        // 查询今天已有的账单数量（假设从数据库查询，或者根据业务需要自定义逻辑生成）
        int existingBillCount = css.count(); // 自定义方法，统计已有的账单数量

        // 生成新的账单编号，格式化为 KHDZ_YYMMdd_001, KHDZ_YYMMdd_002 等
        String billNumber = String.format("KHDZ_%s_%03d", dateStr, existingBillCount + 1);
        return billNumber;
    }

    /**
     * 根据客户对账单id查询对应的对账单和明细
     * */
    @GetMapping("/selectCId")
    public Result selectCId(Integer customerStatementId){
        CustomerStatement c = css.getById(customerStatementId);
        c.setCustomerStatementDetails(csd.selectId(c.getCustomerStatementId()));
        c.setSaleCustomer(sc.getById(c.getCustomerId()));
        return Result.success(200,"success",c);
    }

    /**
     * 修改客户对账单
     * */
    @PostMapping("/updateCustomerStatement")
    public Result updateCustomerStatement(@RequestBody CustomerStatement customerStatement){
        css.updateById(customerStatement);
        return Result.success();
    }

    /**
     * 客户对账单明细分页查询
     * */
    @GetMapping("/selectCustomerStatementDetail")
    public Result selectCustomerStatementDetail(
            @RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "6") Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        PageHelper.orderBy("customer_statement_detail_id desc");
        List<CustomerStatementDetail> list = csd.list();

        for (CustomerStatementDetail c : list) {
            // 设置 CustomerStatement
            c.setCustomerStatement(css.getById(c.getCustomerStatementId()));

            // 设置 Product
            if (c.getProductId() != null) {
                Product product = ps.getById(c.getProductId());
                if (product != null) {
                    c.setProduct(product);
                }
            }

            // 设置 ReceivablePayableDetail
            c.setReceivablePayableDetail(rps.getById(c.getSalesOrderId()));
            ReceivablePayableDetail r = c.getReceivablePayableDetail();
            if (r != null) {
                // 设置 SettlementType 和 BusinessType
                r.setDictData(Arrays.asList(ds.getById(r.getSettlementTypeId()), ds.getById(r.getBusinessTypeId())));
            }

            // 设置 OutboundDetail
            c.setOutboundDetail(outds.getById(c.getOutboundId()));
            OutboundDetail outboundDetail = c.getOutboundDetail();
            if (outboundDetail != null) {
                outboundDetail.setOutboundOrder(oos.getById(outboundDetail.getOutboundOrderId()));
                outboundDetail.setProduct(ps.getById(outboundDetail.getProductId()));
            }

            // 设置 InboundDetail
            c.setInboundDetail(ids.getById(c.getInboundId()));
            InboundDetail inboundDetail = c.getInboundDetail();
            if (inboundDetail != null) {
                inboundDetail.setWarehouseReceipt(wrs.getById(inboundDetail.getInboundOrderId()));
                inboundDetail.setProduct(ps.getById(inboundDetail.getProductId()));
            }
        }

        PageInfo<CustomerStatementDetail> page = new PageInfo<>(list);
        return Result.success(200, "success", page);
    }


    /**
     * 根据客户对账单明细id查询对应的对账单明细
     * */
    @GetMapping("/selectCustomerStatementDetailId")
    public Result selectCustomerStatementDetailId(Integer customerStatementDetailId){
        CustomerStatementDetail c = csd.getById(customerStatementDetailId);
        c.setCustomerStatement(css.getById(c.getCustomerStatementId()));

        // 设置 Product
        if (c.getProductId() != null) {
            Product product = ps.getById(c.getProductId());
            if (product != null) {
                c.setProduct(product);
            }
        }

        // 设置 ReceivablePayableDetail
        c.setReceivablePayableDetail(rps.getById(c.getSalesOrderId()));
        ReceivablePayableDetail r = c.getReceivablePayableDetail();
        if (r != null) {
            // 设置 SettlementType 和 BusinessType
            r.setDictData(Arrays.asList(ds.getById(r.getSettlementTypeId()), ds.getById(r.getBusinessTypeId())));
        }

        // 设置 OutboundDetail
        c.setOutboundDetail(outds.getById(c.getOutboundId()));
        OutboundDetail outboundDetail = c.getOutboundDetail();
        if (outboundDetail != null) {
            outboundDetail.setOutboundOrder(oos.getById(outboundDetail.getOutboundOrderId()));
            outboundDetail.setProduct(ps.getById(outboundDetail.getProductId()));
        }

        // 设置 InboundDetail
        c.setInboundDetail(ids.getById(c.getInboundId()));
        InboundDetail inboundDetail = c.getInboundDetail();
        if (inboundDetail != null) {
            inboundDetail.setWarehouseReceipt(wrs.getById(inboundDetail.getInboundOrderId()));
            inboundDetail.setProduct(ps.getById(inboundDetail.getProductId()));
        }
        return Result.success(200,"success",c);
    }

    /**
     * 添加客户对账单明细
     * */
    @PostMapping("/saveCustomerStatementDetail")
    public Result saveCustomerStatementDetail(@RequestBody CustomerStatementDetail cd){
        csd.save(cd);
        return Result.success();
    }

    /**
     * 修改客户对账单明细
     * */
    @PostMapping("/updateCustomerStatementDetail")
    public Result updateCustomerStatementDetail(@RequestBody CustomerStatementDetail cd){
        csd.updateById(cd);
        return Result.success();
    }
}
